import request from '../util/request';
import { message } from 'antd';

export default {
    namespace: 'book-table-v2',
    state: {
        counter: 0,
        bookList: [],
        statistic:[
            { genre: '淘宝', sold: 275 },
            { genre: '京东', sold: 1150 },
            { genre: '天猫', sold: 120 },
            { genre: '亚马逊', sold: 350 },
            { genre: '当当', sold: 150 },
        ],
    },
    effects: {
        *queryList(_, sagaEffects) {
            const { call, put } = sagaEffects;
            const endPointURI = '/dev/bookList';
            try { // 加入 try catch 捕获抛错
                const bookList = yield call(request, endPointURI);
                yield put({ type: 'loadData', payload: bookList });
            } catch (e) {
                message.error('数据获取失败'); // 打印错误信息
            }
        },
        *getStatistic(_, sagaEffects) {
            const { call, put } = sagaEffects;
            const endPointURI = '/dev/chartData';
            try { // 加入 try catch 捕获抛错
                const chartData = yield call(request, endPointURI);
                yield put({ type: 'afterGetStatistic', payload: chartData });
            } catch (e) {
                message.error('数据获取失败'); // 打印错误信息
            }
        }
    },
    reducers: {
        loadData(state, { payload: bookList }) {
            bookList.forEach(element => {
                element.id = state.counter;
                state.counter += 1;
            });
            return {
                bookList: bookList,
                counter: state.counter,
                statistic: state.statistic
            }
        },
        addOne(state, { payload: newBook }) {
            var newBookList = state.bookList.concat(newBook)
            return {
                bookList: newBookList
            }
        },
        afterGetStatistic(state, { payload: chartData }) {
            debugger;
            var newState = { ...state };
            // newState.statistic=chartData.result;
            return newState;
        }
    }
};